package fr.univ.surveyonline.dispatcher;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.univ.surveyonline.model.Contraintes;
import fr.univ.surveyonline.model.DateHelpers;
import fr.univ.surveyonline.model.PropertiesNumber;
import fr.univ.surveyonline.model.User;
import fr.univ.surveyonline.model.allEnum.AgeEnum;
import fr.univ.surveyonline.model.allEnum.Categorie;
import fr.univ.surveyonline.model.allEnum.Region;
import fr.univ.surveyonline.model.allEnum.SexeEnum;
import fr.univ.surveyonline.question.xmlbuilder.PropertiesBuilder;

public class ContraintesNumberServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String xml = req.getParameter("properties");
		
		PropertiesBuilder p =  new PropertiesBuilder(xml);
		Contraintes c = p.getConstraint();
		List<User> list = PropertiesNumber.sortUser(User.getAllMembers(), DateHelpers.getTodayDate(),c);
		
		PropertiesNumber pn = new PropertiesNumber(list); 

		resp.setContentType("text/xml");
		PrintWriter out = resp.getWriter();
		out.println("<constraint value=\"" + list.size() + "\">");
		addNonRespectedConstraint(pn,c,AgeEnum.values(),out);
		addNonRespectedConstraint(pn,c,Region.values(),out);
		addNonRespectedConstraint(pn,c,Categorie.values(),out);
		addNonRespectedConstraint(pn,c,SexeEnum.values(),out);
		out.println("</constraint>");
	}

	private void addNonRespectedConstraint(PropertiesNumber pn, Contraintes c,
			Object[] values, PrintWriter writer) {
		for (Object o : values) {
			if (!pn.verify(c, o)) {
				writer.print("<non-repected value=\""+ o.toString() +"\">" + pn.getNumberPeople(o) + "</non-repected>");
			}
		}
	}

	
}
